import { getUserInfo } from '@/api/user'
import { createStore } from 'vuex'

export default createStore({
  state: {
    user: null,
    token: localStorage.getItem('token'),
    cart: []
  },
  getters: {
    isLoggedIn: state => !!state.token,
    username: state => state.user?.username || '',
    cartItemCount: state => state.cart.length,
    cartTotal: state => state.cart.reduce((total, item) => total + item.price * item.quantity, 0)
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setToken(state, token) {
      state.token = token
    },
    clearUserData(state) {
      state.user = null
      state.token = null
      localStorage.removeItem('token')
    },
    addToCart(state, product) {
      const existingItem = state.cart.find(item => item.id === product.id && item.type === product.type)
      if (existingItem) {
        existingItem.quantity++
      } else {
        state.cart.push({
          ...product,
          quantity: 1
        })
      }
    },
    removeFromCart(state, { id, type }) {
      const index = state.cart.findIndex(item => item.id === id && item.type === type)
      if (index > -1) {
        state.cart.splice(index, 1)
      }
    },
    updateCartItemQuantity(state, { id, type, quantity }) {
      const item = state.cart.find(item => item.id === id && item.type === type)
      if (item) {
        item.quantity = quantity
      }
    },
    clearCart(state) {
      state.cart = []
    }
  },
  actions: {
    async initApp({ commit, state }) {
      if (state.token) {
        try {
          const user = await getUserInfo()
          commit('setUser', user)
        } catch (error) {
          commit('clearUserData')
        }
      }
    },
    logout({ commit }) {
      commit('clearUserData')
      commit('clearCart')
    },
    async login({ commit }, credentials) {
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(credentials)
      })
      
      if (!response.ok) {
        throw new Error('登录失败')
      }

      const data = await response.json()
      commit('setUser', data.user)
      commit('setToken', data.token)
      localStorage.setItem('token', data.token)
      return data
    },
    async register({ commit }, userData) {
      const response = await fetch('/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
      })

      if (!response.ok) {
        throw new Error('注册失败')
      }

      const data = await response.json()
      commit('setUser', data.user)
      commit('setToken', data.token)
      localStorage.setItem('token', data.token)
      return data
    },
    async fetchUserProfile({ commit }) {
      const token = localStorage.getItem('token')
      if (!token) {
        throw new Error('No token found')
      }

      const response = await fetch('/api/profile', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (!response.ok) {
        throw new Error('获取用户信息失败')
      }

      const data = await response.json()
      commit('setUser', data)
      return data
    },
    async updateUserProfile({ commit }, profileData) {
      const token = localStorage.getItem('token')
      if (!token) {
        throw new Error('No token found')
      }

      const response = await fetch('/api/profile', {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(profileData)
      })

      if (!response.ok) {
        throw new Error('更新用户信息失败')
      }

      const data = await response.json()
      commit('setUser', data)
      return data
    }
  }
}) 